package com.example.springboot.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by wuning at 2018/9/10 17:20
 **/
public class ValidateUtil {

    private ValidateUtil(){}
    private final static class Holder{
        private final static ValidateUtil ins = new ValidateUtil();
    }

    public static ValidateUtil get(){
        return ValidateUtil.Holder.ins;
    }


    private String emailPattern = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
    private String phonePattern = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
    private String namePattern = "^[A-Za-z0-9_-]{3,50}$";//用户名正则，4到16位（字母，数字，下划线，减号）
    private String passwordPattern = "^[a-zA-Z0-9!@#$%^&*_-]{6,20}$";//密码正则，6-20（字母，数字，特殊字符!@#$%^&*_-）


    public boolean matchUsername(String username){
        if (username == null || username.trim().equals("")){
            return false;
        }
        return matches(username, namePattern);
    }

    public boolean matchPassword(String password){
        if (password == null || password.trim().equals("")){
            return false;
        }
        return matches(password, passwordPattern);
    }

    public boolean matchEmail(String email){
        if (email == null || email.trim().equals("")){
            return false;
        }
        return matches(email,emailPattern);
    }

    public boolean matchPhone(String phone){
        if (phone == null || phone.trim().equals("")){
            return false;
        }
        return matches(phone, phonePattern);
    }

    public boolean matches(String text,String pattern){
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(text);
        return m.matches();
    }
}
